package com.hmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.RequestParams;

import com.hmall.feign.clients.ItemClient;
import com.hmall.pojo.ItemDoc;
import com.hmall.pojo.PageResult;
import com.hmall.service.ISearchService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SearchService implements ISearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    @Override
    public void bulkDocumentData(PageDTO<Item> itemDTO) {
        // - 将查询到的商品封装为一个ItemDoc对象，放入ItemDoc集合
        BulkRequest bulk = new BulkRequest();
        for (Item item : itemDTO.getList()) {
            ItemDoc itemDoc = new ItemDoc(item);
            String docJsonString = JSON.toJSONString(itemDoc);
            bulk.add(new IndexRequest("item").id(item.getId().toString()).source(docJsonString, XContentType.JSON));
        }
        //- 将ItemDoc集合批量导入elasticsearch中
        try {
            client.bulk(bulk, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("分页文档新增错误!:{}",e.getMessage());
        }
    }

    @Override
    public PageResult search(RequestParams params) {
        SearchRequest request = new SearchRequest("item");
        String key = params.getKey();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (StringUtils.isNotEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        if (StringUtils.isNotEmpty(params.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }

        if (params.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()));
        }

        if (params.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()));
        }

        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(10f)
                        )
                }
        );

        request.source().query(functionScoreQuery);

        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());

        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        PageResult pageResult = new PageResult();
        SearchHits hits = response.getHits();
        pageResult.setTotal(hits.getTotalHits().value);
        SearchHit[] searchHits = hits.getHits();


        for (SearchHit hit : searchHits) {
            String sourceAsString = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            parseHignlight(hit,itemDoc);
            pageResult.getList().add(itemDoc);
        }

        return pageResult;
    }

    private void parseHignlight(SearchHit hit, ItemDoc itemDoc) {
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        if (!CollectionUtils.isEmpty(highlightFields)) {
            for (String key : highlightFields.keySet()) {
                HighlightField field = highlightFields.get(key);
                if (field != null) {
                    Text[] fragments = field.getFragments();
                    String hightLights = Arrays.stream(fragments).map(Text::string).collect(Collectors.joining(","));

                    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(itemDoc.getClass(), key);

                    Method writeMethod = descriptor.getWriteMethod();
                    try {
                        writeMethod.invoke(itemDoc,hightLights);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public List<String> getSuggestions(String prefix) {

        SearchRequest request = new SearchRequest("item");

        request.source()
                .suggest(new SuggestBuilder().addSuggestion(
                        "suggestions",
                        SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
                ));

        SearchResponse response = null;

        try {
            response = client.search(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("接收返回数据error!");
        }

        Suggest suggest = response.getSuggest();

        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        SearchRequest request = new SearchRequest("item");

        HashMap<String,List<String>> listHashMap = new HashMap<>();

        buildBasicQuery(params,request);

        request.source().size(0);

        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20).order(BucketOrder.count(false)));
        request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20).order(BucketOrder.count(false)));

        SearchResponse response = null;

        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("过滤查询失败!{}",e.getMessage());
        }

        Aggregations aggregations = response.getAggregations();

        List<String> brandAggList = getAggByName(aggregations,"brandAgg");
        List<String> categoryAggList = getAggByName(aggregations, "categoryAgg");

        listHashMap.put("brand",brandAggList);
        listHashMap.put("category",categoryAggList);

        return listHashMap;
    }

    @Override
    public void deleteById(Long id) {
        DeleteRequest item = new DeleteRequest("item").id(id.toString());

        try {
            client.delete(item,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("删除文档error!:{}",e.getMessage());
        }
    }

    @Override
    public void insertById(Long id) {
        IndexRequest request = new IndexRequest("item").id(id.toString());

        Item item = itemClient.getItemById(id);

        ItemDoc itemDoc = new ItemDoc(item);
        request.source(JSON.toJSONString(itemDoc),XContentType.JSON);

        try {
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("新增文档error!:{}",e.getMessage());
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms aggregation = aggregations.get(aggName);

        List<? extends Terms.Bucket> buckets = aggregation.getBuckets();

        ArrayList<String> strings = new ArrayList<>();

        for (Terms.Bucket bucket : buckets) {
            strings.add(bucket.getKeyAsString());
        }
        return strings;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        String key = params.getKey();

        if (StringUtils.isNotEmpty(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category",params.getCategory()));
        }

        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }

        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                            .gte(params.getMinPrice())
                            .lte(params.getMaxPrice())
                            );
        }

        request.source().query(boolQuery);

    }
}
